import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:request_ruoyi/router/router.dart';
import 'package:request_ruoyi/req/login_req.dart';
import 'package:request_ruoyi/uitl/msg.dart';
import 'package:request_ruoyi/store/user_info.dart';

class LoginPhoneNumber extends HookWidget {
  const LoginPhoneNumber({super.key});

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Scaffold(
        appBar: AppBar(title: const Text('手机号登录')),
        body: Center(
          child: SingleChildScrollView(
            padding: const EdgeInsets.all(24),
            child: _LoginForm(),
          ),
        ),
      ),
    );
  }
}

class _LoginForm extends HookWidget {
  const _LoginForm();

  @override
  Widget build(BuildContext context) {
    final formKey = useMemoized(GlobalKey<FormState>.new);
    final phoneCtrl = useTextEditingController();
    final codeCtrl = useTextEditingController();
    final countdown = useState(0);
    final loading = useState(false);
    final loginForm = useState<Map<String, dynamic>>({
      'phoneNumber': '',
      'code': '',
      'uuid': '',
    });

    void readForm() {
      loginForm.value = {
        'phoneNumber': phoneCtrl.text,
        'code': codeCtrl.text,
        'uuid': loginForm.value['uuid'] != '' ? loginForm.value['uuid'] : '',
      };
    }

    void updateCountdown() {
      if (countdown.value > 1) {
        countdown.value--;
        Future<void>.delayed(const Duration(seconds: 1), updateCountdown);
      } else {
        countdown.value = 0;
      }
    }

    // 倒计时功能
    void startCountdown() {
      countdown.value = 60;
      Future<void>.delayed(const Duration(seconds: 1), () {
        updateCountdown();
      });
    }

    // 发送验证码
    Future<void> sendVerificationCode() async {
      if (phoneCtrl.text.isEmpty) {
        ScaffoldMessenger.of(
          context,
        ).showSnackBar(const SnackBar(content: Text('请输入手机号')));
        return;
      }

      if (!RegExp(r'^1[3-9]\d{9}$').hasMatch(phoneCtrl.text)) {
        ScaffoldMessenger.of(
          context,
        ).showSnackBar(const SnackBar(content: Text('请输入正确的手机号')));
        return;
      }

      loading.value = true;
      try {
        readForm();
        // debugPrint('发送验证码请求参数：$loginForm');
        final req = await LoginReq.postPhoneCaptcha(loginForm.value);
        loginForm.value['uuid'] = req['uuid'];
        if (req['uuid'].isNotEmpty) {
          Msg.alert('验证码：${req['code']}');
        } else {
          Msg.alert('验证码发送失败');
        }
      } finally {
        loading.value = false;
      }
    }

    // 登录
    Future<void> login() async {
      if (formKey.currentState!.validate()) {
        // 这里应该调用实际的登录接口
        loading.value = true;
        try {
          readForm();
          debugPrint('登录请求体：$loginForm');
          final req = await LoginReq.loginWithPhone(loginForm.value);
          UserInfo().token = req['token'];
          debugPrint('登录成功响应内容：$req ');
          if (!context.mounted) return;
          // 登录成功后跳转到主页
          const HomeRoute().go(context);
        } finally {
          loading.value = false;
        }
      }
    }

    return Form(
      key: formKey,
      child: Column(
        children: [
          // 手机号输入框
          TextFormField(
            controller: phoneCtrl,
            keyboardType: TextInputType.phone,
            decoration: const InputDecoration(
              labelText: '手机号',
              prefixIcon: Icon(Icons.phone),
              border: OutlineInputBorder(),
            ),
            validator: (value) {
              if (value == null || value.isEmpty) {
                return '请输入手机号';
              }
              if (!RegExp(r'^1[3-9]\d{9}$').hasMatch(value)) {
                return '请输入正确的手机号';
              }
              return null;
            },
          ),
          const SizedBox(height: 20),

          // 验证码输入框
          Row(
            children: [
              Expanded(
                child: TextFormField(
                  controller: codeCtrl,
                  keyboardType: TextInputType.number,
                  decoration: const InputDecoration(
                    labelText: '验证码',
                    prefixIcon: Icon(Icons.lock),
                    border: OutlineInputBorder(),
                  ),
                  validator: (value) {
                    if (value == null || value.isEmpty) {
                      return '请输入验证码';
                    }
                    if (value.length < 4) {
                      return '验证码长度不正确';
                    }
                    return null;
                  },
                ),
              ),
              const SizedBox(width: 10),
              SizedBox(
                width: 100,
                height: 48,
                child: ElevatedButton(
                  onPressed: countdown.value > 0 ? null : sendVerificationCode,
                  child: loading.value
                      ? const SizedBox(
                          width: 20,
                          height: 20,
                          child: CircularProgressIndicator(strokeWidth: 2),
                        )
                      : countdown.value > 0
                      ? Text('${countdown.value}s后重发')
                      : const Text('发送验证码'),
                ),
              ),
            ],
          ),
          const SizedBox(height: 50),

          // 登录按钮
          SizedBox(
            width: double.infinity,
            child: ElevatedButton(
              onPressed: login,
              child: loading.value
                  ? const SizedBox(
                      width: 20,
                      height: 20,
                      child: CircularProgressIndicator(strokeWidth: 2),
                    )
                  : const Text('登录'),
            ),
          ),

          const SizedBox(height: 20),

          // 返回账号登录
          TextButton(
            onPressed: () {
              const LoginRoute().go(context);
            },
            child: const Text('账号密码登录'),
          ),
        ],
      ),
    );
  }
}
